package vn.huync.smsbackupandrestore;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import vn.huync.smsbackupandrestore.models.SmsModel;
import vn.huync.smsbackupandrestore.others.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nch.smsbackupandrestore.R;

public class SearchActivity extends Activity {
	
	String[] listFile;
	MyApp myApp;
	Button bDelete;
	ListView lvFile;
	EditText eInput;
	ArrayList<SmsModel> lResult;
	ArrayList<SmsModel> lAllSms;
	ProgressDialog progressDialog;
	ListSmsAdapter adapter;
	
	static private final int DIALOG_NOTIFICATE_NO_SMS_MATCH = 0;
	static private final int DIALOG_BUSY = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_search_sms);
		
		lvFile = (ListView)findViewById(R.id.l_search);
		
		myApp = (MyApp)getApplicationContext();
		progressDialog = new ProgressDialog(this);

		bDelete = (Button)findViewById(R.id.b_search);
		bDelete.setOnClickListener(onClickListener);
		eInput = (EditText)findViewById(R.id.e_search_input);
		
		lResult = new ArrayList<SmsModel>();
		lAllSms = new ArrayList<SmsModel>();
		
		Thread loadSmsThread =new Thread(new Runnable() {
			
			public void run() {
				File dir = new File(myApp.appFolderPath);
				listFile = dir.list(new FilenameFilter() {
					
					public boolean accept(File dir, String filename) {
						if(filename.endsWith(".xml"))
							return true;
						else return false;
					}
				});
				
				//load all sms from restored files.
				for(int i = 0; i < listFile.length; i++){
					String fileName = listFile[i];
					ArrayList<SmsModel> lSms = Utils.ReadSmsFromSDCardToList(myApp.appFolderPath + fileName);
					SmsModel.addListToList(lAllSms, lSms);
				}
				
				lResult.addAll(lAllSms);
				
				adapter = new ListSmsAdapter(getApplicationContext(), lResult);
				
				runOnUiThread(new Runnable() {
					
					public void run() {
						lvFile.setAdapter(adapter);
					}
				});
			}
		});
		loadSmsThread.start();
		
		eInput.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				processSearch();
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			public void afterTextChanged(Editable s) {
				
			}
		});
		
		AdView adView = (AdView)this.findViewById(R.id.adView);
	    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
	    adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
	    adRequestBuilder.addTestDevice("EEB3EC34691D85EFD1DF789EA3776326");
	    AdRequest adRequest = adRequestBuilder.build();
	    adView.loadAd(adRequest);
	}
	
	protected android.app.Dialog onCreateDialog(int id) 
	{
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getApplicationContext());
		switch (id) {
		case DIALOG_NOTIFICATE_NO_SMS_MATCH:
			dialogBuilder.setMessage(R.string.notification_search_no_result);
			dialogBuilder.setNegativeButton(android.R.string.cancel, null);
			return dialogBuilder.create();
		case DIALOG_BUSY:
			progressDialog.setTitle(R.string.wait_a_few_second);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			return progressDialog;
		default:
			return null;
		}
	};
	
	View.OnClickListener onClickListener = new View.OnClickListener() {
		
		public void onClick(View v) {
			eInput.setText("");
		}
	};
	
	void processSearch(){
		String sInput = eInput.getText().toString();
		lResult.clear();
		
		for(SmsModel sms:lAllSms){
			
			//content match
			String content = sms.getBody();
			
			if(content.indexOf(sInput) != -1){
				lResult.add(sms);
				continue;
			}
			
			//address match 
			String address = sms.getAddress();
			
			if(address.indexOf(sInput) != -1){
				lResult.add(sms);
				continue;
			}
			
			//name match
			String name = Utils.GetDisplayNameOfAddress(sms.getAddress(), myApp.lContact);
			
			if(name.indexOf(sInput) != -1){
				lResult.add(sms);
				continue;
			}
		}
		
		if(adapter != null)
			adapter.notifyDataSetChanged();
	}
	
	class ListSmsAdapter extends ArrayAdapter<SmsModel>{
		Context context;
		int textViewResourceId;
		List<SmsModel> lSmsShow;
		
		public ListSmsAdapter(Context context, List<SmsModel> lSmsShow) {
			super(context, R.layout.row_sms_detail, lSmsShow);
			this.context = context;
			this.lSmsShow = lSmsShow;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if(row == null){
				LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
				row = inflater.inflate(R.layout.row_sms_detail, null);
				
				TextView tName = (TextView) row.findViewById(R.id.row_sms_detail_name);
				TextView tDate = (TextView) row.findViewById(R.id.row_sms_detail_date);
				TextView tContent = (TextView) row.findViewById(R.id.row_sms_detail_content);
				
				RowWrapper wrapper = new RowWrapper();
				wrapper.tName = tName;
				wrapper.tDate = tDate;
				wrapper.tContent = tContent;
				row.setTag(wrapper);
			}
			
			RowWrapper wrapper = (RowWrapper)row.getTag();
			TextView tName = wrapper.tName;
			TextView tDate = wrapper.tDate;
			TextView tContent = wrapper.tContent;
			
			SmsModel sms = lSmsShow.get(position);
			//name
			
			if(sms.getType() == 1){			//receive
				String contactName = Utils.GetDisplayNameOfSms(sms, myApp.lContact);
				if(contactName != "")
					tName.setText(Html.fromHtml("<b>" + contactName + " : </b>"));
				else  tName.setText(Html.fromHtml("<b>" + sms.getAddress() + " : </b>"));
			}
			else{							//send
				tName.setText(Html.fromHtml("<b>" + getString(R.string.me) + " : </b>"));
			}
			//date
			final Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(sms.getDate());
			Date date = cal.getTime();
			String sDate = date.getDate() + "/" + date.getMonth() + "/" + (date.getYear()+1900) + " "+
							date.getHours() + ":" + date.getMinutes();

			tDate.setText(sDate);
			
			tContent.setText(sms.getBody());
			
			return row;
		}
	}
	
	class RowWrapper{
		public TextView tName;
		public TextView tDate;
		public TextView tContent;
	}
}
